<template>
  <div class="form-data">
    <a-form
      ref="formRef"
      v-bind="options"
      :layout="options?.layout"
      :model="insideModel"
    >
      <a-form-item
        v-bind="item"
        :label="item.label"
        v-for="(item, index) in option"
        :key="index"
      >
        <component
          v-bind="item"
          :value="insideModel && insideModel[item.prop]"
          @update:value="(v) => changeValue(item, v)"
          :is="getCom(item)"
        ></component>
      </a-form-item>
      <a-form-item>
        <div
          style="display: flex; align-items: center;"
          v-if="options?.showBtn"
        >
          <a-button @click="resetForm"> 重置 </a-button>
          <div>&nbsp;</div>
          <a-button type="primary" @click="submit">
            {{ options?.submitName || "提交" }}
          </a-button>
          <!--具名插槽-->
        </div>
        <div style="display: flex; align-items: center;">
          <slot name="menuForm"></slot>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts">
import * as _ from "lodash";
import { computed, defineComponent, PropType, ref } from "vue";
import { columns, options, FormParsingProps } from "./type";

export default defineComponent({
  props: {
    columns: Array as PropType<Array<columns>>,
    options: Object as PropType<options>,
    modelValue: Object,
  },
  name: "FromParsing",
  setup(props, { emit }) {
    const insideModel = computed(() => {
      return props.modelValue;
    });
    const formRef = ref();
    const option = computed<any>(() => {
      //支持直接传columns 也可以采用 options来进行配置，options支持更多的功能
      if (props.columns) {
        return props.columns;
      } else {
        return props.options?.columns;
      }
    });
    const values = computed(() => {
      if (!(props.modelValue instanceof Array)) {
        return [props.modelValue];
      }
    });
    const getCom = (item: any) => {
      if (item.component) {
        return item.component;
      }
      switch (item.type) {
        case "dynamic":
          return "FormParsing";
        case "checkbox":
          return "DCheckBox";
        case "radio":
          return "DRadio";
        case "select":
          return "DSelect";
        default:
          return `a-${item.type || "a-input"}`;
      }
    };

    const submit = () => {
      emit("submit", insideModel.value);
    };

    const changeValue = (item: any, v: any) => {
      //重新创建一个值 修改并 emit
      let model = JSON.parse(JSON.stringify(props.modelValue));
      model[item.prop] = v;
      emit("update:modelValue", model);
    };

    const resetForm = () => {
      for (const key in insideModel.value) {
        insideModel.value[key] = "";
      }
      emit("update:modelValue", insideModel.value);
    };
    return {
      option,
      getCom,
      values,
      changeValue,
      submit,
      insideModel,
      resetForm,
      formRef,
    };
  },
});
</script>
<style scoped></style>
